import React, { useState, useCallback, useMemo, useEffect } from 'react';
import { Link } from 'react-router-dom';
import { GroupName, Groups, Config } from '../types.ts';
import Wheel from '../components/Wheel.tsx';
import NameModal from '../components/NameModal.tsx';
import ResultModal from '../components/ResultModal.tsx';
import DrawEndModal from '../components/DrawEndModal.tsx';
import AlreadyDrawnModal from '../components/AlreadyDrawnModal.tsx';
import { TrophyIcon } from '../components/icons/TrophyIcon.tsx';
import { UsersIcon } from '../components/icons/UsersIcon.tsx';
import * as api from '../utils/api.ts';

const DrawPage: React.FC = () => {
  const [groups, setGroups] = useState<Groups>({});
  const [config, setConfig] = useState<Config | null>(null);
  const [isNameModalOpen, setIsNameModalOpen] = useState(false);
  const [isResultModalOpen, setIsResultModalOpen] = useState(false);
  const [isDrawEndModalOpen, setIsDrawEndModalOpen] = useState(false);
  const [isAlreadyDrawnModalOpen, setIsAlreadyDrawnModalOpen] = useState(false);
  const [isSpinning, setIsSpinning] = useState(false);
  const [spinResult, setSpinResult] = useState<GroupName | null>(null);
  const [lastResult, setLastResult] = useState<{ name: string, group: GroupName } | null>(null);
  const [alreadyDrawnName, setAlreadyDrawnName] = useState<string>('');
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);

  const drawnCount = useMemo(() => {
    return Object.values(groups).reduce((sum, members) => sum + members.length, 0);
  }, [groups]);

  const totalSlots = config?.total_participants || 30;
  const isDrawComplete = useMemo(() => drawnCount >= totalSlots, [drawnCount, totalSlots]);

  // 初始化数据
  useEffect(() => {
    const initializeData = async () => {
      try {
        const [configData, groupsData] = await Promise.all([
          api.getConfig(),
          api.getGroups()
        ]);
        setConfig(configData);
        setGroups(groupsData);
      } catch (error) {
        console.error('初始化数据失败:', error);
        setError('加载数据失败，请刷新页面重试');
      } finally {
        setLoading(false);
      }
    };

    initializeData();
  }, []);

  // 移动端滚动控制
  useEffect(() => {
    // 防止移动端页面滚动
    const preventScroll = (e: TouchEvent) => {
      if (isSpinning) {
        e.preventDefault();
      }
    };

    // 当转盘开始转动时，禁用页面滚动
    if (isSpinning) {
      document.body.style.overflow = 'hidden';
      document.body.style.position = 'fixed';
      document.body.style.width = '100%';
      document.body.style.top = '0';

      // 添加触摸事件监听器
      document.addEventListener('touchmove', preventScroll, { passive: false });

      // 确保页面滚动到顶部
      window.scrollTo(0, 0);
    } else {
      // 转盘停止时，恢复页面滚动
      document.body.style.overflow = '';
      document.body.style.position = '';
      document.body.style.width = '';
      document.body.style.top = '';

      // 移除触摸事件监听器
      document.removeEventListener('touchmove', preventScroll);
    }

    // 清理函数
    return () => {
      document.removeEventListener('touchmove', preventScroll);
      document.body.style.overflow = '';
      document.body.style.position = '';
      document.body.style.width = '';
      document.body.style.top = '';
    };
  }, [isSpinning]);

  // 定期刷新分组数据
  useEffect(() => {
    const interval = setInterval(async () => {
      // 如果当前正在抽签，跳过刷新
      if (isSpinning) {
        return;
      }

      try {
        const groupsData = await api.getGroups();
        setGroups(groupsData);
      } catch (error) {
        console.error('刷新分组数据失败:', error);
      }
    }, 5000); // 每5秒刷新一次

    return () => clearInterval(interval);
  }, [isSpinning]); // 添加 isSpinning 依赖

  const handleDrawClick = useCallback(() => {
    if (isSpinning || loading) return;

    if (isDrawComplete) {
      // 如果摇号已完成，直接显示结束弹窗
      setIsDrawEndModalOpen(true);
      return;
    }

    // 确保页面在顶部
    window.scrollTo(0, 0);
    setError(null);
    setIsNameModalOpen(true);
  }, [isDrawComplete, isSpinning, loading]);

  const handleNameSubmit = useCallback(async (name: string) => {
    const trimmedName = name.trim();
    if (!trimmedName) {
      setError('请输入队长姓名');
      return;
    }

    setIsNameModalOpen(false);
    setError(null);

    try {
      // 先调用后台摇号接口获取结果
      const result = await api.draw({ name: trimmedName });

      if (result.success && result.group && result.groups) {
        // 确保页面在顶部并设置转盘转动
        window.scrollTo(0, 0);
        setSpinResult(result.group);
        setIsSpinning(true);

        // 等待转盘动画完成后显示结果
        setTimeout(() => {
          setIsSpinning(false);

          // 设置结果并显示模态框
          setLastResult({ name: trimmedName, group: result.group! });
          setIsResultModalOpen(true);
        }, 4000); // 转盘动画持续4秒
      } else {
        // 摇号失败，检查是否是摇号结束
        const errorMessage = result.error || '摇号失败，请重试';
        if (errorMessage.includes('摇号已结束') || errorMessage.includes('所有名额已满')) {
          // 摇号已结束，关闭名称弹窗并显示结束弹窗
          setIsNameModalOpen(false);
          setIsDrawEndModalOpen(true);
        } else if (errorMessage.includes('已经摇过号')) {
          // 重复摇号，显示已摇号弹窗
          setAlreadyDrawnName(trimmedName);
          setIsAlreadyDrawnModalOpen(true);
        } else {
          // 其他错误，显示错误信息
          setError(errorMessage);
        }
      }
    } catch (error) {
      console.error('摇号请求失败:', error);
      setError('网络错误，请重试');
    }
  }, []);

  const handleCloseResultModal = useCallback(() => {
    setIsResultModalOpen(false);
    setLastResult(null);
    
    // 延迟更新分组数据，确保动画完成
    setTimeout(async () => {
      try {
        const groupsData = await api.getGroups();
        setGroups(groupsData);
      } catch (error) {
        console.error('更新分组数据失败:', error);
      }
    }, 500);
  }, []);

  const handleCloseDrawEndModal = useCallback(() => {
    setIsDrawEndModalOpen(false);
  }, []);

  const handleCloseAlreadyDrawnModal = useCallback(() => {
    setIsAlreadyDrawnModalOpen(false);
    setAlreadyDrawnName('');
  }, []);

  if (loading) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-slate-900 via-blue-900 to-slate-900 flex items-center justify-center">
        <div className="text-white text-xl">加载中...</div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-900 via-blue-900 to-slate-900 flex flex-col items-center justify-center p-4 relative overflow-hidden"
         style={{
           touchAction: 'manipulation', // 防止双击缩放
           userSelect: 'none', // 防止选择文本
           overscrollBehavior: 'none', // 防止过度滚动
         }}>
      {/* 背景装饰 */}
      <div className="absolute inset-0 overflow-hidden pointer-events-none">
        <div className="absolute -top-40 -right-40 w-80 h-80 bg-blue-500/10 rounded-full blur-3xl"></div>
        <div className="absolute -bottom-40 -left-40 w-80 h-80 bg-purple-500/10 rounded-full blur-3xl"></div>
        <div className="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 w-96 h-96 bg-yellow-500/5 rounded-full blur-3xl"></div>
      </div>

      <header className="text-center z-10 mb-4 md:mb-2">
        <div className="flex items-center justify-center gap-2 sm:gap-3">
            <TrophyIcon className="w-8 h-8 sm:w-10 sm:h-10 text-yellow-400" />
            <h1 className="text-3xl sm:text-4xl md:text-5xl font-bold tracking-tight bg-clip-text text-transparent bg-gradient-to-r from-yellow-300 to-yellow-500">
                储能羽毛球大赛分组抽签
            </h1>
        </div>
        <p className="text-slate-400 mt-2 text-sm sm:text-base">
            剩余名额: {totalSlots - drawnCount} / {totalSlots}
        </p>
      </header>
      
      <main className="flex flex-col items-center justify-center w-full flex-grow z-10">
        <div className="relative flex flex-col items-center justify-center mb-8">
            <Wheel isSpinning={isSpinning} result={spinResult} groups={config?.groups || []} />
        </div>
        
        <button
          onClick={handleDrawClick}
          disabled={isDrawComplete || isSpinning}
          className="relative inline-flex items-center justify-center px-10 py-4 text-lg font-bold text-white transition-all duration-200 bg-blue-600 rounded-full focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-slate-900 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed disabled:animate-none hover:bg-blue-700"
        >
          <span className={`absolute h-full w-full rounded-full bg-blue-500 ${isSpinning || isDrawComplete ? '' : 'animate-ping'}`}></span>
          <span className="relative">
            {isDrawComplete ? '抽签完成' : isSpinning ? '正在抽签...' : '开始抽签'}
          </span>
        </button>

        {/* 分组情况入口 */}
        <div className="mt-6">
          <Link
            to="/groups"
            className="flex items-center gap-2 px-6 py-3 bg-slate-800/50 backdrop-blur-sm rounded-lg border border-slate-700 text-slate-300 hover:text-white hover:bg-slate-700/50 transition-all duration-300"
          >
            <UsersIcon className="w-5 h-5" />
            <span>查看分组情况</span>
          </Link>
        </div>
      </main>

      {/* 错误提示 */}
      {error && (
        <div className="fixed top-4 right-4 bg-red-500 text-white px-4 py-2 rounded-lg shadow-lg z-50">
          {error}
        </div>
      )}

      <NameModal
        isOpen={isNameModalOpen}
        onClose={() => setIsNameModalOpen(false)}
        onSubmit={handleNameSubmit}
        error={error}
      />

      <ResultModal
        isOpen={isResultModalOpen}
        onClose={handleCloseResultModal}
        result={lastResult}
      />

      <DrawEndModal
        isOpen={isDrawEndModalOpen}
        onClose={handleCloseDrawEndModal}
        totalParticipants={totalSlots}
      />

      <AlreadyDrawnModal
        isOpen={isAlreadyDrawnModalOpen}
        onClose={handleCloseAlreadyDrawnModal}
        name={alreadyDrawnName}
      />
    </div>
  );
};

export default DrawPage;
